package com.juyu.miliao.scheduler.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.constant.UserVipMqKey;
import com.juyu.miliao.common.delay.DelayMessage;
import com.juyu.miliao.common.domain.dto.UserVipMqMessage;
import com.juyu.miliao.scheduler.service.VipExpireService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.ZoneOffset;

/**
 * @author xuanqicheng
 */
@Component
@Slf4j
public class UserVipMq {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private VipExpireService vipExpireService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(UserVipMqKey.USER_VIP_INFO_QUEUE_KEY),
            exchange = @Exchange(UserVipMqKey.USER_VIP_INFO_EXCHANGE_KEY),
            key =UserVipMqKey.USER_VIP_INFO_ROUTING_KEY))
    public void getUserVipMqMessage(String message){
        if(!StringUtils.isEmpty(message)){
            try {
                UserVipMqMessage userVipMqMessage =objectMapper.readValue(message,UserVipMqMessage.class);
                DelayMessage<Integer> delayMessage = new DelayMessage<Integer>(userVipMqMessage.getUserVipId(),
                        userVipMqMessage.getUserVipId(),
                        userVipMqMessage.getExpireTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
                vipExpireService.putDelayMessage(delayMessage);

            }catch (Exception ex){
                log.error("处理寻user_vip错误："+message+"|erro="+ex.getMessage());
            }
        }
    }
}
